import React, { FC, useMemo, useEffect } from 'react';
import { SetterHoc } from '../../../common';
import { TreeSelect } from 'antd';
import { usePropsValue, useReRenderEvent } from '../../../_hooks';
import { clearCache, useRequest } from 'ahooks';
import { Request } from '../../../../src/components/utils/request';
import { API_URL } from '../../config';

export async function getTable(params: any) {
  return Request.get<any>(API_URL + `/table/get`, { params });
}
export interface IColumnSelectSetterProps {
  value: string[];
  onChange: (value: string[]) => void;
}

export interface IUseTableDataOptions {
  namescpace?: string;
}

/**
 * 获取表格数据
 * @param tableId
 */
export const useTableData = (tableId: string, options?: IUseTableDataOptions) => {
  const { namescpace = 'brick' } = options || {};
  const cacheKey = `${namescpace}-table-${tableId}`;

  const { data, loading, run } = useRequest(getTable, {
    manual: true,
    cacheKey,
  });

  useEffect(() => {
    if (tableId) {
      run({ id: tableId, hasSchema: false });
    }

    return () => {
      clearCache(cacheKey);
    };
  }, [tableId]);

  return { table: data, loading };
};

const getChildren = (column: any) => {
  if (column.fieldType === 'RELATION') {
    const relationConfig = column.columnConfig as any;
    return (
      relationConfig?.displayFields?.map?.((item) => {
        return {
          key: item.id,
          title: item.title,
          value: item.id,
        };
      }) || []
    );
  }

  return [];
};

const ColumnSelectSetterFun: FC<IColumnSelectSetterProps> = (props) => {
  const { getPropValue } = usePropsValue(props);
  const relationTableId = getPropValue('columnConfig.relationTableId');

  const { table } = useTableData(relationTableId);

  useReRenderEvent();

  const treeData = useMemo(() => {
    if (!table) {
      return [];
    }
    const result: Array<any> = [];
    table?.columns?.forEach?.((item) => {
      result.push({
        key: item.id,
        title: item.title,
        value: item.id,
        children: getChildren(item),
      });
    });
    return result;
  }, [table]);

  // 获取所有table columns信息
  const onChange = (newValue: string[]) => {
    console.log('onChange ', newValue);
    props?.onChange?.(newValue);
  };

  const tProps = {
    treeData,
    value: props?.value,
    // size: 'small',
    onChange,
    // maxTagPlaceholder: '112',
    treeCheckable: true,
    showCheckedStrategy: TreeSelect.SHOW_ALL,
    placeholder: '请选择',
    multiple: true,
    maxTagCount: 1,
    style: {
      width: '100%',
    },
  };

  return <TreeSelect {...tProps} size={'small'} />;
};

export const ColumnSelectSetter = SetterHoc(ColumnSelectSetterFun);
